package br.sed.theenemy.presentation.servlets;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.sed.theenemy.business.exception.DBException;
import br.sed.theenemy.business.services.Services;
import br.sed.theenemy.business.utils.Utils;
import br.sed.theenemy.model.bean.User;
import br.sed.theenemy.presentation.EnemyConstants;
import br.sed.theenemy.presentation.EnemyErrorConstants;
import br.sed.theenemy.presentation.action.json.exception.ExpectedException;
import br.sed.theenemy.presentation.action.json.exception.IdentifiedException;
import br.sed.theenemy.presentation.servlets.json.JSONBaseServlet;
import br.sed.theenemy.presentation.vo.UserVO;

/**
 * 
 * @author JulioCB
 * @email jcbjulio@gmail.com
 * 
 */
@WebServlet("/findRandom")
public class FindRandomServlet extends JSONBaseServlet {

	private static final long serialVersionUID = 2195651709376810965L;

	@Override
	protected Object executeJSON(HttpServletRequest request,
			HttpServletResponse response) throws ExpectedException,
			IdentifiedException {
		Services services = Services.getInstance();
		
		List<String> errors =  new ArrayList<String>();
		errors = validate(request);
		if (errors.size()!=0){
			throw new ExpectedException(EnemyErrorConstants.MISSING_PARAM, errors);
		}
		Integer max = Integer.parseInt(request.getParameter("max"));
		if (max == null || max <= 0 || max > EnemyConstants.MAX_PAGE_ITENS){
			throw new ExpectedException(EnemyErrorConstants.INCORRECT_PARAM);
		}
		
		List<User> userList = null;
		try {
			 userList = services.findUserRandom(max);
		} catch (DBException e) {
			throw new ExpectedException(EnemyErrorConstants.DB_EXCEPTION);
		}
		
		List<UserVO> userListVO = new ArrayList<UserVO>();
		for (User user: userList){
			UserVO userVO = new UserVO(user);
			userListVO.add(userVO);
		}

		return userListVO;
	}
	private List<String> validate(HttpServletRequest request){
		List<String> errors = new ArrayList<String>();
		if(Utils.isNullOrEmptyOrNotNumber(request.getParameter("max"))){
			errors.add("Missing Page");
		}
		return errors;
	}
}
